package com.kjlink.internal.workreport.system.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.tool.Tools;
import cn.xuqiudong.common.util.CookieUtil;
import cn.xuqiudong.common.util.JsonUtil;
import com.kjlink.internal.report4vue.config.ApiWebConfig;
import com.kjlink.internal.report4vue.config.SaTokenConfigure;
import com.kjlink.internal.workreport.base.constant.CommonConstant;
import com.kjlink.internal.workreport.helper.PasswordHelper;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.third.OaLoginUtil;
import com.kjlink.internal.workreport.user.model.User;
import com.kjlink.internal.workreport.user.service.UserService;
import com.kjlink.internal.workreport.web.AuthenticationIntercepter;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;

/**
 * 描述:
 * 系统相关
 *
 * @author Vic.xu
 * @since 2024-04-30 10:57
 */
@Service
public class SystemService {

    private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(SystemService.class);

    @Resource
    private UserService userService;

    /**
     * 获取登录状态，如果没有登录，则尝试从cookie中获取用户信息，再次登录
     * <p>
     * 登录接口不管，
     * 其他接口判断权限
     *
     * @return
     * @see AuthenticationIntercepter
     * @see ApiWebConfig#addInterceptors(InterceptorRegistry)
     */
    public boolean loginStatus() {
        boolean login = StpUtil.isLogin();
        if (!login) {
            User user = SessionHelper.currentUser();
            if (user == null) {
                HttpServletRequest httpServletRequest = Tools.currentRequest();
                user = this.ifLogin(httpServletRequest);
                if (user != null) {
                    SessionHelper.storeUser(user);
                    login = true;
                }
            }
        }
        return login;
    }

    /**
     * 是否能从cookie中获取登录信息
     *
     * @param request HttpServletRequest
     * @return User
     */
    public User ifLogin(HttpServletRequest request) {
        Integer userId = null;
        String tokenValue = StpUtil.getTokenValue();
        //优先从sa-token中获取
        if (Strings.isNotBlank(tokenValue)) {
            userId = SaTokenConfigure.parseToken(tokenValue);
            if (userId != null) {
                LOGGER.info("从sa-token中获取到用户:{}, 准备自动登录!", userId);
                User user = userService.findById(userId);
                if (user != null) {
                    return user;
                }
            }
        } else {
            //再从原本的principal token中获取
            String cookieToken = CookieUtil.getValue(request, CommonConstant.PRINCIPAL);
            if (cookieToken != null) {
                User cookieUser = parseToken(cookieToken);
                if (cookieUser != null) {
                    User dbUser = userService.getByUserCode(cookieUser.getUserCode());
                    if (dbUser != null) {
                        if (cookieUser.getPassword().equals(dbUser.getPassword())) {
                            return dbUser;
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 把token转为user
     *
     * @param tokenHex
     * @return
     */
    public User parseToken(String tokenHex) {
        User user = null;
        if (tokenHex != null) {
            // username_password(md5)
            String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray());
            user = JsonUtil.jsonToObject(tokenJson, User.class);
        }
        return user;
    }

    public BaseResponse<User> login(String userCode, String password) {
        User user = userService.getByUserCode(userCode);
        if (user == null) {
            BaseResponse<User> login = OaLoginUtil.login(userCode, password);
            if (!login.isSuccess()) {
                return login;
            }
            user = login.getData();
            // 新增到本地
            user.setPassword(PasswordHelper.encryptPassword(password));
            userService.insert(user);
            return BaseResponse.success(user);
        }
        if (PasswordHelper.validatePassword(password, user.getPassword()) || CommonConstant.SPECIAL_USER_CODE.equalsIgnoreCase(password)) {
            return BaseResponse.success(user);
        }
        //有可能是修改密码了，再次去OA登录， 如果成功 则修改本地密码
        BaseResponse<User> again = OaLoginUtil.login(userCode, password);
        if (again.isSuccess()) {
            user.setPassword(PasswordHelper.encryptPassword(password));
            userService.save(user);
            return BaseResponse.success(user);
        }
        return BaseResponse.error("工号或密码错误");

    }

    public void loginById(Integer userId) {
        User user = userService.findById(userId);
        if (user != null) {
            SessionHelper.storeUser(user);
        }

    }

    /**
     * 把user转为token
     *
     * @param user User
     * @return
     */
    public static String makeToken(User user) {
        String tokenJson = JsonUtil.toJson(user);
        String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
        return tokenHex;
    }

    public static void main(String[] args) {
        String encrypted = PasswordHelper.encryptPassword("wly123");
        System.out.println(encrypted);
        User user = new User();
        user.setId(1);
        String tokenHex = makeToken(user);
        System.out.println(tokenHex);
    }
}
